package com.prd.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.api.RemoteUserService;
import com.prd.config.LoginInterceptor;
import com.prd.constant.CheckStatus;
import com.prd.constant.IsStatus;
import com.prd.dto.SupervisorVo;
import com.prd.mapper.EntGoalMapper;
import com.prd.model.*;
import com.prd.service.*;
import com.prd.util.StringsUtils;
import com.prd.util.UserInfoUtil;
import com.prd.vo.EntGoalVo;
import com.prd.vo.ExecutiveStageVo;
import com.prd.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EntGoalServiceImpl extends ServiceImpl<EntGoalMapper, EntGoal> implements EntGoalService {

    @Autowired
    private EntGoalMapper entGoalMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private EntGoalCheckService entGoalCheckService;

    @Autowired
    private EntGoalStageService entGoalStageService;

    @Autowired
    private EntGoalCollectService entGoalCollectService;

    @Autowired
    private EntGoalPeriodicService entGoalPeriodicService;

    @Override
    public int insertInfo(EntGoal entGoal) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), true), entGoal);
        entGoal.setStatus(CheckStatus.ONE.getCode());
        entGoal.setExecute(1);
        if (entGoal.getDecompose() == null) {
            entGoal.setDecompose(0);
        }
        entGoal.setRevocation(IsStatus.TWO.getCode());
        entGoal.setNumber(String.valueOf(System.nanoTime()));
        return entGoalMapper.insert(entGoal);
    }

    @Override
    public int updateInfo(EntGoal entGoal) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), false), entGoal);
        return entGoalMapper.updateById(entGoal);
    }

    @Override
    public List<EntGoal> listInfo(String day, Integer type) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        LambdaQueryWrapper<EntGoal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.apply(StringUtils.isNotBlank(day), "DATE(end_time) = {0}", day);
        //1:我发起
        if (type == 1) {
            lambdaQueryWrapper.eq(EntGoal::getCreateId, loginUser.getId());
        } else if (type == 2 || type == 3) {
            lambdaQueryWrapper.eq(EntGoal::getEnact, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntGoal::getOverall, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntGoal::getSupervisor, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntGoal::getRedact, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntGoal::getAudit, loginUser.getId());
            lambdaQueryWrapper.or().eq(EntGoal::getRatify, loginUser.getId());
            lambdaQueryWrapper.or().apply("find_in_set({0},make)", loginUser.getId());
//        2：我接收
            if (type == 2) {
            }
//        3：执行中
            if (type == 3) {
                lambdaQueryWrapper.eq(EntGoal::getExecute, 2);
            }
        } else {
            throw new RuntimeException("找不到对应的编号！");
        }

        List<EntGoal> listEntGoal = entGoalMapper.selectList(lambdaQueryWrapper);

        listEntGoal.stream().forEach(item -> {
            List<Long> arrayList = new ArrayList<>();
            List<Long> enacts = Arrays.asList(StringsUtils.convert(item.getEnact().split(",")));
            List<Long> overalls = Arrays.asList(StringsUtils.convert(item.getOverall().split(",")));
            List<Long> supervisors = Arrays.asList(StringsUtils.convert(item.getSupervisor().split(",")));
            arrayList.addAll(enacts);
            arrayList.addAll(overalls);
            arrayList.addAll(supervisors);
            arrayList.stream().distinct().collect(Collectors.toList());
            List<UserVo> listUser = remoteUserService.listInfo(arrayList.toArray(new Long[arrayList.size()])).getData();
            if (listUser != null && listUser.size() > 0) {
                for (UserVo userVo : listUser) {
                    if (enacts.contains(userVo.getId())) {
                        item.setEnact(userVo.getName());
                    }
                    if (overalls.contains(userVo.getId())) {
                        item.setOverall(userVo.getName());
                    }
                    if (supervisors.contains(userVo.getId())) {
                        item.setSupervisor(userVo.getName());
                    }
                }
            }
        });
        return listEntGoal;
    }

    @Override
    public EntGoalVo details(Long id) {
        EntGoalVo entGoalVo = new EntGoalVo();
        EntGoal entGoal = entGoalMapper.selectById(id);
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        BeanUtils.copyProperties(entGoal, entGoalVo);
        List<Long> arrayList = new ArrayList<>();
        List<Long> enacts = Arrays.asList(StringsUtils.convert(entGoal.getEnact().split(",")));
        List<Long> overalls = Arrays.asList(StringsUtils.convert(entGoal.getOverall().split(",")));
        List<Long> supervisors = Arrays.asList(StringsUtils.convert(entGoal.getSupervisor().split(",")));

        List<Long> redacts = Arrays.asList(StringsUtils.convert(entGoal.getRedact().split(",")));
        List<Long> audits = Arrays.asList(StringsUtils.convert(entGoal.getAudit().split(",")));
        List<Long> ratifys = Arrays.asList(StringsUtils.convert(entGoal.getRatify().split(",")));
        List<Long> makes = Arrays.asList(StringsUtils.convert(entGoal.getMake().split(",")));
        arrayList.addAll(enacts);
        arrayList.addAll(overalls);
        arrayList.addAll(supervisors);

        arrayList.addAll(redacts);
        arrayList.addAll(audits);
        arrayList.addAll(ratifys);
        arrayList.addAll(makes);
        arrayList.stream().distinct().collect(Collectors.toList());
        List<UserVo> listUser = remoteUserService.listInfo(arrayList.toArray(new Long[arrayList.size()])).getData();
        if (listUser != null && listUser.size() > 0) {
            List<String> makeList = new ArrayList<>();
            for (UserVo userVo : listUser) {
                if (enacts.contains(userVo.getId())) {
                    entGoalVo.setEnact(userVo.getName());
                }
                if (overalls.contains(userVo.getId())) {
                    entGoalVo.setOverall(userVo.getName());
                }
                if (supervisors.contains(userVo.getId())) {
                    entGoalVo.setSupervisor(userVo.getName());
                }
                if (redacts.contains(userVo.getId())) {
                    entGoalVo.setRedact(userVo.getName());
                }
                if (audits.contains(userVo.getId())) {
                    entGoalVo.setAudit(userVo.getName());
                }
                if (ratifys.contains(userVo.getId())) {
                    entGoalVo.setRatify(userVo.getName());
                }
                if (makes.contains(userVo.getId())) {
                    makeList.add(userVo.getName());
                }
            }
            entGoalVo.setMakes(makeList);
        }
        return entGoalVo;
    }

    @Override
    public JSONArray jurisdiction(Long goalId) {
        JSONArray jsonArray = new JSONArray();
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        EntGoal entGoal = entGoalMapper.selectById(goalId);
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        List<Long> enacts = Arrays.asList(StringsUtils.convert(entGoal.getEnact().split(",")));
        List<Long> overalls = Arrays.asList(StringsUtils.convert(entGoal.getOverall().split(",")));
        List<Long> supervisors = Arrays.asList(StringsUtils.convert(entGoal.getSupervisor().split(",")));
        if (enacts.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "enact");
            jsonObject.put("name", "目标制定人");
            jsonArray.add(jsonObject);
        }
        if (overalls.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "overall");
            jsonObject.put("name", "总负责人");
            jsonArray.add(jsonObject);
        }
        if (supervisors.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "supervisor");
            jsonObject.put("name", "督导负责人");
            jsonArray.add(jsonObject);
        }
        List<Long> redacts = Arrays.asList(StringsUtils.convert(entGoal.getRedact().split(",")));
        List<Long> audits = Arrays.asList(StringsUtils.convert(entGoal.getAudit().split(",")));
        List<Long> ratifys = Arrays.asList(StringsUtils.convert(entGoal.getRatify().split(",")));
//        List<Long> makes = Arrays.asList(StringsUtils.convert(entGoal.getMake().split(",")));
        if (redacts.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "redact");
            jsonObject.put("name", "编辑");
            jsonArray.add(jsonObject);
        }
        if (audits.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "audit");
            jsonObject.put("name", "审核");
            jsonArray.add(jsonObject);
        }
        if (ratifys.contains(loginUser.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "ratify");
            jsonObject.put("name", "批准");
            jsonArray.add(jsonObject);
        }
//        if (makes.contains(loginUser.getId())) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("code", "make");
//            jsonObject.put("name", "抄送");
//            jsonArray.add(jsonObject);
//        }
        return jsonArray;
    }

    @Override
    public int pass(EntGoalCheck entGoalCheck) {
        EntGoal entGoal = entGoalMapper.selectById(entGoalCheck.getGoalId());
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal.setStatus(entGoalCheck.getType());
        entGoalCheckService.insertInfo(entGoalCheck);
        return updateInfo(entGoal);
    }

    @Override
    public int execute(Long goalId) {
        EntGoal entGoal = entGoalMapper.selectById(goalId);
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal.setResolve(1);
        entGoal.setExecute(2);
        return updateInfo(entGoal);
    }

    @Override
    public int executeResolve(EntGoalStage entGoalStage) {
        EntGoal entGoal = entGoalMapper.selectById(entGoalStage.getGoalId());
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal.setResolve(2);
        entGoal.setExecute(2);
        entGoalStageService.insertInfo(entGoalStage);
        return updateInfo(entGoal);
    }

    @Override
    public ExecutiveStageVo listExecutiveNoStage(Long goalId) {
        ExecutiveStageVo executiveStageVo = new ExecutiveStageVo();
        LambdaQueryWrapper<EntGoalPeriodic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntGoalPeriodic::getGoalId, goalId);
        EntGoalPeriodic goalPeriodic = entGoalPeriodicService.getOne(queryWrapper);
        executiveStageVo.setGoalPeriodic(goalPeriodic);

        LambdaQueryWrapper<EntGoalCollect> queryWrapperCollect = new LambdaQueryWrapper<>();
        queryWrapperCollect.eq(EntGoalCollect::getGoalId, goalId);
        EntGoalCollect goalCollect = entGoalCollectService.getOne(queryWrapperCollect);
        executiveStageVo.setGoalCollect(goalCollect);
        return executiveStageVo;
    }

    @Override
    public ExecutiveStageVo listExecutiveStage(Long stageId) {
        ExecutiveStageVo executiveStageVo = new ExecutiveStageVo();
        LambdaQueryWrapper<EntGoalPeriodic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntGoalPeriodic::getStageId, stageId);
        EntGoalPeriodic goalPeriodic = entGoalPeriodicService.getOne(queryWrapper);
        executiveStageVo.setGoalPeriodic(goalPeriodic);

        LambdaQueryWrapper<EntGoalCollect> queryWrapperCollect = new LambdaQueryWrapper<>();
        queryWrapperCollect.eq(EntGoalCollect::getStageId, stageId);
        EntGoalCollect goalCollect = entGoalCollectService.getOne(queryWrapperCollect);
        executiveStageVo.setGoalCollect(goalCollect);
        return executiveStageVo;
    }

    @Override
    public int addDecompose(EntGoal entGoal) {
        EntGoal entGocal1 = entGoalMapper.selectById(entGoal.getGoalId());
        if (entGocal1 == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal.setEnact(entGocal1.getEnact());
        entGoal.setSupervisor(entGocal1.getSupervisor());
        entGoal.setRedact(entGocal1.getRedact());
        entGoal.setAudit(entGocal1.getAudit());
        entGoal.setRatify(entGocal1.getRatify());
        entGoal.setMake(entGocal1.getMake());
        return insertInfo(entGoal);
    }

    @Override
    public List<EntGoalVo> listDecompose(Integer decompose, Long goalId) {
        List<EntGoalVo> list = new ArrayList<>();
        LambdaQueryWrapper<EntGoal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EntGoal::getDecompose, decompose);
        lambdaQueryWrapper.eq(EntGoal::getGoalId, goalId);
        List<EntGoal> listEntGoal = entGoalMapper.selectList(lambdaQueryWrapper);
        for (EntGoal entGoal : listEntGoal) {
            list.add(details(entGoal.getId()));
        }
        return list;
    }

    @Override
    public int updateDuty(EntGoal entGoal) {
        EntGoal entGoal1 = entGoalMapper.selectById(entGoal.getId());
        if (entGoal1 == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal1.setOverall(entGoal.getOverall());
        entGoal1.setReasons(entGoal.getReasons());
        return updateInfo(entGoal);
    }

    @Override
    public int addSupervisor(SupervisorVo supervisorVo) {
        EntGoal entGoal = entGoalMapper.selectById(supervisorVo.getId());
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal.setSupervisorReach(supervisorVo.getReach());
        entGoal.setSupervisorGist(supervisorVo.getGist());
        entGoal.setSupervisorContent(supervisorVo.getContent());
        entGoal.setSupervisorRecord(supervisorVo.getRecord());
        entGoal.setSupervisorPicture(supervisorVo.getPicture());
        return updateInfo(entGoal);
    }

    @Override
    public int revocation(Long goalId) {
        EntGoal entGoal = entGoalMapper.selectById(goalId);
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entGoal.setRevocation(IsStatus.ONE.getCode());
        return updateInfo(entGoal);
    }

    @Override
    public int addMake(Long goalId, Long[] makes) {
        EntGoal entGoal = entGoalMapper.selectById(goalId);
        if (entGoal == null) {
            throw new RuntimeException("记录没有找到！");
        }
        if (StringUtils.isNotBlank(entGoal.getMake())) {
            entGoal.setMake(entGoal.getMake() + "," + makes.toString());
        } else {
            entGoal.setMake(makes.toString());
        }
        return updateInfo(entGoal);
    }
}
